<?php
/**
 * @Author: Ron Chen
 * @Date:   2016-12-13 21:40:11
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2016-12-13 21:48:10
 */


namespace common\helpers;

class ImageHelper {
	
	const FILE_EXTENSIONS_JPG  = 1;
	const FILE_EXTENSIONS_JPEG = 2;
	const FILE_EXTENSIONS_GIF  = 3;
	const FILE_EXTENSIONS_PNG  = 4;
	const FILE_EXTENSIONS_BMP  = 5;

	public static $allow_file_ext = [
		self::FILE_EXTENSIONS_JPG  => "jpg",
		self::FILE_EXTENSIONS_JPEG => "jpeg",
		self::FILE_EXTENSIONS_GIF  => "gif",
		self::FILE_EXTENSIONS_PNG  => "png",
		self::FILE_EXTENSIONS_BMP  => "bmp"
	];


	/**
	 * 文件本地保存
	 * @param $file_name   上传的文件原始文件名
	 * @param $tmp_name    上传的临时文件
	 * @param $file_dir    文件存储路径
	 * $file = UploadedFile::getInstanceByName('attach'); //yii操作文件对象
	 */
	public static function fileUploadLocal($file_name,$tmp_name,$file_dir){
		if (self::checkFileExt($file_name)) {
			// 生成随机的文件名
			$file_ext   = self::getFileExt($file_name);
			$save_name  = StringHelper::generateFilename();
			$upload_name= sprintf("%s%s.%s",$file_dir,$save_name,$file_ext);
			if (move_uploaded_file($tmp_name,$upload_name)){
				if(is_uploaded_file($tmp_name){
					return $upload_name;
				}
    		}
		}

    	return false;
	}


	/**
	 * base64加密上传
	 * @param $file 当前上传的额文件对象
	 * @return $data 加密的对象
	 * $file = UploadedFile::getInstanceByName('attach'); //yii操作文件对象
	 */
	public static function fileUploadBase64($file){
		$data = (object)array();
		$attach = explode(';',$file);
		if(!isset($attach[0])){
            return ['code'=>-1,'msg'=>'文件为空'];
        }
        $postfix   = explode('/',$attach[0]);
        if(!isset($postfix[1])){
            return ['code'=>-1,'msg'=>'文件格式错误'];
        }
        if(!in_array($postfix[1], self::$allow_file_ext)){
            return ['code'=>-1,'msg'=>'文件格式不符合要求'];
        }
        $img  = str_replace("{$attach[0]};base64,", '', $attach);
    	$img  = str_replace(' ', '+', $img);
    	$data = base64_decode($img);
        
        return ['code'=>0,'msg'=>'success','data'=>$data];
	}





	/**
	 * 检查文件是否是合法的后缀
	 */
	public static function checkFileExt($file_name){
		if (strpos($file_name, '.') !== false){
			$file_ext = self::getFileExt($file_name);

			if (in_array($file_ext, self::$allow_file_ext)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取文件后缀名
	 */
	public static function getFileExt($file_name){
		return mb_strtolower(substr($file_name, strrpos($file_name, '.') + 1));
	}
}